﻿using PagedList;
using PagedList.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace System.Web.Mvc
{
    public static class StaticPagedListExtendMethods
    {
        static readonly PagedListRenderOptions defaultOptions = new PagedListRenderOptions
        {
            DisplayLinkToFirstPage = PagedListDisplayMode.Always,
            DisplayLinkToLastPage = PagedListDisplayMode.Always,
            LinkToFirstPageFormat = "首页",
            LinkToLastPageFormat = "尾页",
            LinkToPreviousPageFormat = "<<",
            LinkToNextPageFormat = ">>",
            MaximumPageNumbersToDisplay = 5,
            Display = PagedListDisplayMode.IfNeeded
        };
        public static MvcHtmlString PagedListPager(this System.Web.Mvc.HtmlHelper html, IPagedList list)
        {
            if (list == null || list.TotalItemCount == 0)
            {
                return MvcHtmlString.Empty;
            }

            Func<int, string> generatePageUrl = (page =>
            {
                var url = HttpContext.Current.Request.RawUrl;
                var pageParam = "page=" + page.ToString();

                if (url.IndexOf("page=", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    return Regex.Replace(url, @"page=\d*", pageParam, RegexOptions.IgnoreCase);
                }
                else
                {
                    if (url.IndexOf("?") >= 0)
                    {
                        return url + "&" + pageParam;
                    }
                    else
                    {
                        return url + "?" + pageParam;
                    }
                }
            });
            return html.PagedListPager(list, generatePageUrl, defaultOptions);
        }

        public static StaticPagedList<TModel> ToStaticPagedList<TModel>(this Loogn.OrmLite.OrmLitePageResult<TModel> pr)
        {
            return new StaticPagedList<TModel>(pr.List, pr.PageIndex, pr.PageSize, (int)pr.TotalCount);
        }
    }
}
